import { Link } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { Card, Breadcrumb, Form, Button, Radio, DatePicker, Select } from 'antd'
import locale from 'antd/es/date-picker/locale/zh_CN'
// 导入资源
import { Table, Tag, Space } from 'antd'
import { FileSearchOutlined } from '@ant-design/icons'
import './index.scss'
import DrawerAgain from '@/pages/Check/components/DrawerAgain'
import labelList from '@/utils/lable'
import { getAllBlogAPI } from '@/api/blog'
import dayjs from 'dayjs'
import { getBlogByLabelAPI } from '@/api/label'
import moment from 'moment'

const { Option } = Select
const { RangePicker } = DatePicker

const Check = () => {

    // 分页
    const [params, setParams] = useState({
      page: 1,
      per_page: 5,
    })
    const pageChange = (page) => {
      // 拿到当前页参数 修改params
      setParams({
        ...params,
        page
      })
  }

  // 获取所有博客
  const [blogInfo, setBlogInfo] = useState([])
  const getBlogInfo = async () => {
    try {
      const res = await getAllBlogAPI()
      const filterArr = res.data.filter((item) => item.state !== "草稿")
      setBlogInfo(filterArr.sort((a, b) => moment(b.createTime).diff(moment(a.createTime))).map((item) => {
        return { 
          ...item, 
          createTime: dayjs(item.createTime).format('YYYY-MM-DD'),
          // text: item.text.replace(/<img[^>]+>|<br>/g, '') 
        }
      }))
        // 通过时间对博客进行排序
        blogInfo.sort((a, b) => moment(b.createTime).diff(moment(a.createTime)))
    } catch (error) {
      console.error('Error fetching blog info', error)
    }
  }
   
  useEffect(() => {
    (async () => {
      await getBlogInfo()  // 使用立即执行的匿名函数
    })()
  }, [])

    // 准备列数据
  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      width: 260
    },
    {
      title: '作者',
      dataIndex: 'author',
      width: 260
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 260,
      render: (data) => {
        return (
          <div>
            {data === '已发布' && <Tag color="green">{data}</Tag>}
            {data === '审核中' && <Tag color="gold">{data}</Tag>}
            {data === '下架' && <Tag color="red">{data}</Tag>}
          </div>
        )
      }
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      width: 300
    },
    // {
    //   title: '博客内容',
    //   ellipsis: true,
    //   dataIndex: 'text'
    // },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size="middle">
            <Button 
            type="primary" 
            icon={<FileSearchOutlined />} 
            onClick={() => showDrawer(data)}
            >查看详情
            </Button>
          </Space>
        )
      }
    }
  ]

  // 筛选数据
  const hanldleFilter = async (formValue) => {
    const begin = formValue.date && dayjs(formValue.date[0]).format('YYYY-MM-DD')
    const end = formValue.date && dayjs(formValue.date[1]).format('YYYY-MM-DD')
    try {
      let filteredData = []
  
      if (formValue.state !== '全部') {
        const res1 = await getAllBlogAPI({ state: formValue.state || '', begin: begin || '', end: end || '' })
        filteredData = res1.data.filter((item) => item.state !== "草稿")
      } else {
        const resAll = await getAllBlogAPI({ begin: begin || '', end: end || '' })
        filteredData = resAll.data.filter((item) => item.state !== "草稿")
      }
  
      if (formValue.label) {
        const resByLabel = await getBlogByLabelAPI(formValue.label)
        filteredData = filteredData.filter((item) => resByLabel.data.some((labelItem) => labelItem.id === item.id))
      }
      
      setBlogInfo(filteredData.sort((a, b) => moment(b.createTime).diff(moment(a.createTime))).map((item) => {
        return { 
          ...item, 
          createTime: dayjs(item.createTime).format('YYYY-MM-DD'),
          // text: item.text.replace(/<img[^>]+>|<br>/g, '') 
        }
      }))
    } catch (error) {
      console.error('Error filtering blog', error)
    }
  }

    //   抽屉组件
    const [open, setOpen] = useState(false)
    const [checkBlog, setCheckBlog] = useState({})
    const showDrawer = (data) => {
      console.log(data);
      setOpen(true)
      setCheckBlog(data)
    }
    const closeDrawer = (value) => {
      setOpen(value)
      getBlogInfo()
    }

    // 更新博客
    const handleCheckInfoChange = () => {
      getBlogInfo()
    }
    
    return (
        <div>
          <Card
            title={
              <Breadcrumb items={[
                { title: <Link to={'/'}>首页</Link> },
                { title: '博客审核' },
              ]} />
            }
            style={{ marginBottom: 20 }}
          >
            <Form 
              initialValues={{ status: '' }}
              onFinish={hanldleFilter}>
              <Form.Item label="状态" name="state" initialValue="全部">
                <Radio.Group >
                  <Radio value={'全部'}>全部</Radio>
                  <Radio value={'审核中'}>待审核</Radio>
                  <Radio value={'已发布'}>审核通过</Radio>
                  <Radio value={'下架'}>已下架</Radio>
                </Radio.Group>
              </Form.Item>
    
              <Form.Item label="分类" name="label">
                <Select
                  placeholder="请选择文章分类"
                  style={{ width: 120 }}
                >
                  <Option value=''>全部</Option>
                  {labelList.map(item => (
                    <Option key={item.id} value={item.name}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
    
              <Form.Item label="日期" name="date">
                {/* 传入locale属性 控制中文显示*/}
                <RangePicker locale={locale}></RangePicker>
              </Form.Item>
    
              <Form.Item>
                <Button type="primary" htmlType="submit" style={{ marginLeft: 40 }}>
                  筛选
                </Button>
              </Form.Item>
            </Form>
            <Table 
              rowKey="id" 
              columns={columns} 
              dataSource={blogInfo} 
              pagination={{
                current: params.page,
                pageSize: params.per_page,
                onChange: pageChange,
                total: blogInfo.length
              }}/>
            {Object.keys(checkBlog) && <DrawerAgain 
              open={open} 
              closeDrawer={closeDrawer}
              checkBlog={checkBlog}
              onUpdate={handleCheckInfoChange}></DrawerAgain>}
          </Card>
        </div>
      )
    }
    

export default Check